import { defineStore } from 'pinia'
import { ref } from 'vue'
import request from '../utils/request'

export const useUserStore = defineStore('user', () => {
  const currentUser = ref(null)
  const isLogin = ref(false)
  const error = ref(null)
  const isInitialized = ref(false)

  // 用户活动数据
  const userLikes = ref([])
  const userSubscriptions = ref([])
  const userComments = ref([])
  const userShares = ref([])
  const userFollowers = ref([])

  // 初始化认证状态
  const initializeAuth = async () => {
    // 如果已经初始化过，直接返回
    if (isInitialized.value) {
      return Promise.resolve(isLogin.value)
    }
    
    try {
      const savedUser = localStorage.getItem('user')
      if (savedUser) {
        currentUser.value = JSON.parse(savedUser)
        currentUser.value.id = Number(currentUser.value.id)
        isLogin.value = true
      }
    } catch (error) {
      console.error('初始化用户状态失败:', error)
      localStorage.removeItem('user')
    } finally {
      isInitialized.value = true
    }
    
    return isLogin.value
  }

  // 用户登录
  const login = async (account, password) => {
    try {
    
      const data = await request.post('/users/login', { account, password })
      currentUser.value = data
      console.log(account,password);
      
      isLogin.value = true
      error.value = null
      // 存储用户信息到 localStorage
      localStorage.setItem('user', JSON.stringify(data))

      return data
    } catch (error) {
      console.error('登录失败:', error)
      error.value = error.response?.data?.error || '登录失败'
      throw error
    }
  }

  // 退出登录
  const logout = () => {
    currentUser.value = null
    isLogin.value = false
    error.value = null
    localStorage.removeItem('user')
  }

  // 关注用户
  const followUser = async (userId) => {
    try {
      const data = await request.post(`/users/${currentUser.value.id}/subscribe/${userId}`)
      return data
    } catch (err) {
      console.error('关注用户失败:', err)
      throw err
    }
  }

  // 取消关注用户
  const unfollowUser = async (userId) => {
    try {
      const data = await request.delete(`/users/${currentUser.value.id}/subscribe/${userId}`)
      return data
    } catch (err) {
      console.error('取消关注失败:', err)
      throw err
    }
  }

  // 检查是否已关注某用户
  const checkIsFollowing = async (userId) => {
    try {
      const  data  = await request.get(
        `/users/${currentUser.value.id}/isSubscribed/${userId}`
      )
      return data.isSubscribed
    } catch (err) {
      console.error('检查关注状态失败:', err)
      throw err
    }
  }

  // 更新用户头像
  const updateAvatar = async (userId, file) => {
    try {
      const formData = new FormData()
      formData.append('avatar', file)
      
      const { avatar } = await request.post(
        `/users/${userId}/avatar`,
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
      )

      // 更新本地用户数据
      if (currentUser.value && currentUser.value.id === userId) {
        currentUser.value.avatar = avatar
        // 更新localStorage中的用户信息
        localStorage.setItem('user', JSON.stringify(currentUser.value))
      }

      return avatar
    } catch (err) {
      console.error('更新头像失败:', err)
      throw err
    }
  }

  // 获取用户喜欢的文章列表
  const fetchUserLikes = async (userId) => {
    try {
      const data = await request.get(`/users/${userId}/likes`)
      userLikes.value = data
      return data
    } catch (err) {
      console.error('获取喜欢列表失败:', err)
      throw err
    }
  }

  // 获取用户的订阅列表
  const fetchUserSubscriptions = async (userId) => {
    try {
      const data = await request.get(`/users/${userId}/subscriptions`)
      userSubscriptions.value = data
      return data
    } catch (err) {
      console.error('获取订阅列表失败:', err)
      throw err
    }
  }

  // 获取用户的评论列表
  const fetchUserComments = async (userId) => {
    try {
      const data = await request.get(`/users/${userId}/comments`)
      userComments.value = data
      return data
    } catch (err) {
      console.error('获取评论列表失败:', err)
      throw err
    }
  }

  // 获取用户的转发列表
  const fetchUserShares = async (userId) => {
    try {
      const data = await request.get(`/users/${userId}/shares`)
      userShares.value = data
      return data
    } catch (err) {
      console.error('获取转发列表失败:', err)
      throw err
    }
  }

  // 获取用户的粉丝列表
  const fetchUserFollowers = async (userId) => {
    try {
      const data = await request.get(`/users/${userId}/followers`)
      userFollowers.value = data
      return data
    } catch (err) {
      console.error('获取粉丝列表失败:', err)
      throw err
    }
  }

  // 获取用户的所有活动数据
  const fetchUserAllActivities = async (userId) => {
    try {
      await Promise.all([
        fetchUserLikes(userId),
        fetchUserSubscriptions(userId),
        fetchUserComments(userId),
        fetchUserShares(userId),
        fetchUserFollowers(userId)
      ])
    } catch (err) {
      console.error('获取用户活动数据失败:', err)
      throw err
    }
  }

  return {
    currentUser,
    isLogin,
    error,
    isInitialized,
    login,
    logout,
    initializeAuth,
    followUser,
    unfollowUser,
    checkIsFollowing,
    updateAvatar,
    // 用户活动数据
    userLikes,
    userSubscriptions,
    userComments,
    userShares,
    userFollowers,
    // 获取用户活动数据的方法
    fetchUserLikes,
    fetchUserSubscriptions,
    fetchUserComments,
    fetchUserShares,
    fetchUserFollowers,
    fetchUserAllActivities
  }
}) 